<?php
/*
 * coding: utf-8
 * +-------------------------------------------------------------------
 * | KL库 - MYSQL，MYSQLI，SQLITE模块
 * +-------------------------------------------------------------------
 * | Copyright (c) 2022-2099 KL库(https://www.fangheyun.xyz) All rights reserved.
 * +-------------------------------------------------------------------
 * | Author: 远易 <3431628590@qq.com>
 * +-------------------------------------------------------------------
 */

if(DB_SWITCH){
	if(DB_TYPE == 'MYSQL'){
		exit("ERROR: MySQL extension has been abolished, please use advanced mysqli extension");
	}else if(DB_TYPE == 'MYSQLI'){
		class DB {
			var $link = null;
			function __construct($db_host,$db_user,$db_pass,$db_name,$db_port){
				$this->link = mysqli_connect($db_host, $db_user, $db_pass, $db_name, $db_port);
				if ($this->link){
					mysqli_query($this->link,"set sql_mode = ''");
					mysqli_query($this->link,"set character set 'utf8'");
					mysqli_query($this->link,"set names 'utf8'");
					return true;
				}else{
					exit('ERROR: '.mysqli_connect_error());
				}
			}
			/**
			 * 获取 Mysql连接对象
			 */
			public function db_sql($object=''){
				if($object == ''){
					return $this->link;
				}else{
					if(is_array($object)){
						if($object['DB_HOST'] == '' || $object['DB_HOST'] == NULL){
							$object['DB_HOST'] = '127.0.0.1';
						}else if(!is_string($object['DB_HOST'])){
							exit('ERROR: The type of "DB_HOST" should be a string');
						}else if($object['DB_PORT'] == '' || $object['DB_PORT'] == NULL){
							$object['DB_PORT'] = 3306;
						}else if(!is_int($object['DB_PORT'])){
							exit('ERROR: The type of "DB_PORT" should be a int');
						}else if($object['DB_USER'] == '' || $object['DB_USER'] == NULL){
							exit('ERROR: "DB_USER" should not be empty');
						}else if(!is_string($object['DB_USER'])){
							exit('ERROR: The type of "DB_USER" should be a string');
						}else if($object['DB_PASS'] == '' || $object['DB_PASS'] == NULL){
							exit('ERROR: "DB_PASS" should not be empty');
						}else if(!is_string($object['DB_PASS'])){
							exit('ERROR: The type of "DB_PASS" should be a string');
						}else if($object['DB_NAME'] == '' || $object['DB_NAME'] == NULL){
							exit('ERROR: "DB_NAME" should not be empty');
						}else if(!is_string($object['DB_NAME'])){
							exit('ERROR: The type of "DB_NAME" should be a string');
						}else{
							return mysqli_connect($object['DB_HOST'], $object['DB_USER'], $object['DB_PASS'], $object['DB_NAME'], $object['DB_PORT']);
						}
					}else{
						exit("ERROR: Custom database objects must be associative arrays, DB_ Host is the address. The default is 127.0.0.1. It can be empty. DB_ Port is the port, which is 3306 by default. It can be empty, but DB_ User (user name), DB_ Pass (password), DB_ Name (name) must be passed!");
					}
				}
			}
			/**
			 * 获取数据表的数据，只可以用表值来获取信息
			 * @result 附属方法
			 */
			public function fetch($result=''){
				if($result == ''){
					exit('ERROR: Subsidiary method cannot be empty');
				}
				return mysqli_fetch_assoc($result);
			}
			/**
			 * 获取数据表的数据，可以用0123...或表值来获取信息
			 * @result 附属方法
			 */
			public function fetchs($result=''){
				if($result == ''){
					exit('ERROR: Subsidiary method cannot be empty');
				}
				return mysqli_fetch_array($result);
			}
			/**
			 * 获取数据表的数据
			 * @table 将要查询数据表数量的表名
			 * @array 条件数组
			 * 注: @array 若非数组则返回整张数据表的数据
			 * @db_sql 新数据库对象
			 */
			public function get_row($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$list = "`$key`='$value' AND ".$list;
					}
					$list = substr($list,0,-4);
					$sql = "SELECT * FROM `$table` WHERE $list";
				}else{
					$sql = "SELECT * FROM `$table`";
				}
				if($db_sql == ''){
					$result = mysqli_query($this->link,$sql);
				}else{
					$result = mysqli_query($db_sql,$sql);
				}
				return mysqli_fetch_assoc($result);
			}
			/**
			 * 获取数据表中的数量
			 * @table 将要查询数据表数量的表名
			 * @array 条件数组
			 * 注: @array 若非数组则返回整张数据表的数量
			 * @db_sql 新数据库对象
			 */
			public function num_row($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$list = "`$key`='$value' AND ".$list;
					}
					$list = substr($list,0,-4);
					$sql = "SELECT * FROM `$table` WHERE $list";
				}else{
					$sql = "SELECT * FROM `$table`";
				}
				if($db_sql == ''){
					$result = mysqli_query($this->link,$sql);
				}else{
					$result = mysqli_query($db_sql,$sql);
				}
				return mysqli_num_rows($result);
			}
			/**
			 * 获取数据表中的某一条
			 * @table 将要查询数据表数量的表名
			 * @num 某一条  注: 默认为0，相当于第一条
			 * @array 条件数组
			 * 注: @array 若非数组则返回整张数据表的数据
			 * @db_sql 新数据库对象
			 */
			public function count($table='',$num=0,$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$list = "`$key`='$value' AND ".$list;
					}
					$list = substr($list,0,-4);
					$sql = "SELECT * FROM `$table` WHERE $list";
				}else{
					$sql = "SELECT * FROM `$table`";
				}
				if($db_sql == ''){
					$result = mysqli_query($this->link,$sql);
				}else{
					$result = mysqli_query($db_sql,$sql);
				}
				return mysqli_fetch_array($result)[$num];
			}
			/**
			 * SQl语句执行
			 * @sql 将要执行的SQL语句
			 * @db_sql 新数据库对象
			 */
			public function query($sql='',$db_sql=''){
				if($sql == ''){
					exit('ERROR: SQL statement cannot be empty');
				}
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * fetch、fetchs 的附属方法
			 * @table 将要查询数据表数量的表名
			 * @array 条件数组
			 * 注: @array 若非数组则返回整张数据表的数据
			 * @db_sql 新数据库对象
			 */
			public function query_se($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$list = "`$key`='$value' AND ".$list;
					}
					$list = substr($list,0,-4);
					$sql = "SELECT * FROM `$table` WHERE $list";
				}else{
					$sql = "SELECT * FROM `$table`";
				}
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 字符串转义
			 * 1. 防止SQL Injection攻击，也就是你必须验证用户的输入
			 * 2. 操作数据的时候避免不必要的字符导致错误
			 * @str 字符串
			 * @db_sql 新数据库对象
			 */
			public function escape($str='',$db_sql=''){
				if($str == ''){
					exit('ERROR: String cannot be empty');
				}
				if($db_sql == ''){
					return mysqli_real_escape_string($this->link,$str);
				}else{
					return mysqli_real_escape_string($db_sql,$str);
				}
			}
			/**
			 * 插入数据表并获取插入后的ID
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
			 * @db_sql 新数据库对象
			 */
			public function insert($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(!is_array($array)){
					exit('ERROR: Incorrect data format');
				}
				$sql = "INSERT INTO `$table`";
				$sql .=" (`".implode("`,`",array_keys($array))."`) ";
				$sql .=" VALUES ('".implode("','",array_values($array))."') ";
				if($db_sql == ''){
					if(mysqli_query($this->link,$sql))
						return mysqli_insert_id($this->link); 
				}else{
					if(mysqli_query($db_sql,$sql))
						return mysqli_insert_id($db_sql); 
				}
				return false;
			}
			/**
			 * 常用于执行SQL语句后，返回受影响的行数
			 * @db_sql 新数据库对象
			 */
			public function affected($db_sql=''){
				if($db_sql == ''){
					return mysqli_affected_rows($this->link);
				}else{
					return mysqli_affected_rows($db_sql);
				}
			}
			/**
			 * 获取整张表的数据
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量可自定义，value值需对应数据表中的值
			 * @judge (True，False) 注: 默认为False，为True时（key变量）与（value值）相同不可改变，False反之
			 * @db_sql 新数据库对象
			 */
			public function json_array($table='',$array='',$judge=False,$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if($db_sql == ''){
					$sql = mysqli_query($this->link,"SELECT * FROM $table");
				}else{
					$sql = mysqli_query($db_sql,"SELECT * FROM $table");
				}
				if(is_array($array)){
					while($arr = mysqli_fetch_assoc($sql)){
						foreach($array as $key=>$value)
						{
							if($judge){
								$arrays[$value] = $arr[$value];
							}else{
								$arrays[$key] = $arr[$value];
							}
						}
						$list = json_encode($arrays, JSON_UNESCAPED_UNICODE).','.$list;
					}
				}else{
					while($arr = mysqli_fetch_assoc($sql)){
						$list = json_encode($arr, JSON_UNESCAPED_UNICODE).','.$list;
					}
				}
				return json_decode('['.substr($list,0,-1).']',true);
			}
			/**
			 * 搜索数据
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
			 * @arrays 数组(key变量=>value值) 注: key变量可自定义，value值需对应数据表中的值
			 * @judge (True，False) 注: 默认为False，为True时（key变量）与（value值）相同不可改变，False反之
			 * @db_sql 新数据库对象
			 */
			public function search_array($table='',$array='',$arrays='',$judge=False,$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$lists = "$key LIKE '%$value%' AND ".$lists;
					}
					if($db_sql == ''){
						$sql = mysqli_query($this->link,"SELECT * FROM $table WHERE ".substr($lists,0,-4));
					}else{
						$sql = mysqli_query($db_sql,"SELECT * FROM $table WHERE ".substr($lists,0,-4));
					}
				}else{
					if($db_sql == ''){
						$sql = mysqli_query($this->link,"SELECT * FROM $table");
					}else{
						$sql = mysqli_query($db_sql,"SELECT * FROM $table");
					}
				}
				if(is_array($arrays)){
					while($arr = mysqli_fetch_assoc($sql)){
						foreach($arrays as $keys=>$values)
						{
							if($judge){
								$arrayss[$values] = $arr[$values];
							}else{
								$arrayss[$keys] = $arr[$values];
							}
						}
						$list = json_encode($arrayss, JSON_UNESCAPED_UNICODE).','.$list;
					}
				}else{
					while($arr = mysqli_fetch_assoc($sql)){
						$list = json_encode($arr, JSON_UNESCAPED_UNICODE).','.$list;
					}
				}
				return json_decode('['.substr($list,0,-1).']',true);
			}
			/**
			 * 插入数据
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
			 * @db_sql 新数据库对象
			 */
			public function insert_array($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(!is_array($array)){
					exit('ERROR: Incorrect data format');
				}
				$sql = "INSERT INTO `$table`";
				$sql .=" (`".implode("`,`",array_keys($array))."`) ";
				$sql .=" VALUES ('".implode("','",array_values($array))."') ";
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 编辑数据
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量是数据表的值，value值则是数据表值的内容
			 * @arrays 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
			 * @db_sql 新数据库对象
			 */
			public function modify_array($table='',$array='',$arrays='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(!is_array($array)){
					exit('ERROR: Incorrect data format');
				}
				foreach($array as $key=>$value)
				{
					$list = "`$key`='$value', ".$list;
				}
				$list = substr($list,0,-2);
				if(is_array($arrays)){
					foreach($arrays as $keys=>$values)
					{
						$lists = "`$keys`='$values' AND ".$lists;
					}
					$lists = substr($lists,0,-4);
					$sql = "UPDATE `$table` SET $list WHERE $lists";
				}else{
					$sql = "UPDATE `$table` SET $list";
				}
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 删除数据
			 * @table 数据表名
			 * @array 数组(key变量=>value值) 注: key变量需对应数据表中的值，value值则是条件（例: key变量是否等于value值）
			 * @db_sql 新数据库对象
			 */
			public function delete_array($table='',$array='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				if(is_array($array)){
					foreach($array as $key=>$value)
					{
						$list = "`$key`='$value' AND ".$list;
					}
					$list = substr($list,0,-4);
					$sql = "DELETE FROM `$table` WHERE $list";
				}else{
					exit('ERROR: To delete all data in the data table, use the "empty" function');
				}
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 清空数据表
			 * @table 数据表名
			 * @db_sql 新数据库对象
			 */
			public function empty_table($table='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				$sql = "TRUNCATE $table";
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 删除数据表  注: 谨慎使用！！！
			 * @table 数据表名
			 * @db_sql 新数据库对象
			 */
			public function delete_table($table='',$db_sql=''){
				if($table == ''){
					exit('ERROR: Data table name cannot be empty');
				}
				$sql = "DROP TABLE $table";
				if($db_sql == ''){
					return mysqli_query($this->link,$sql);
				}else{
					return mysqli_query($db_sql,$sql);
				}
			}
			/**
			 * 获取报错信息，常用于执行SQL语句之后返回报错信息
			 * @db_sql 新数据库对象
			 */
			public function error($db_sql=''){
				if($db_sql == ''){
					$error = mysqli_error($this->link);
					$errno = mysqli_errno($this->link);
				}else{
					$error = mysqli_error($db_sql);
					$errno = mysqli_errno($db_sql);
				}
				return 'ERROR: ('.$errno.')'.$error;
			}
			/**
			 * 关闭数据库连接
			 * @db_sql 新数据库对象
			 */
			public function close($db_sql=''){
				if($db_sql == ''){
					$sql = mysqli_close($this->link);
				}else{
					$sql = mysqli_close($db_sql);
				}
				return $sql;
			}
		}
	}else if(DB_TYPE == 'SQLITE'){
		exit("ERROR: Temporarily discard SQLite");
	}else{
		exit("ERROR: The database type can only be MySQL, mysqli, SQLite");
	}
}
?>